package com.bw.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;

import org.ietf.jgss.Oid;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerUtil {
	public static void genHtml(ServletContext ctx,String ftlPath,
			String ftlName,String htmlPath,Map map) {
		try {
			//1.定义Configuration
			Configuration conf = new Configuration(Configuration.VERSION_2_3_26);
			conf.setEncoding(Locale.getDefault(), "UTF-8");
			//2.设置模板加载器
			conf.setServletContextForTemplateLoading(ctx, ftlPath);//ftl存放的位置classpath路径
			//3.根据模板名称获取模板对象Template
			Template tmpl = conf.getTemplate(ftlName);//生成的模板对象
			//4.生成静态HTMl文件
			//从map数据模型中获取id
			Integer id = (Integer)map.get("id");
			String path = ctx.getRealPath(htmlPath);//生成静态网页的绝对路径 
			System.out.println("path====="+path);//path=====D:\eclipseawork\eclipseworkspase9_e_commerce\proj_Good01\src\main\webapp\html
			String htmlFile = path+"/"+id+".html";
			FileOutputStream fos = new FileOutputStream(htmlFile);
			OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF8");
			//5.模板对象整合静态与资源map
			tmpl.process(map, osw);
			//关闭文件
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//删除
	public static void delHtml(ServletContext ctx,String htmlPath,Integer id) {
		try {
			String path = ctx.getRealPath(htmlPath);
			String file = path+"/"+id+".html";
			File f = new File(file);
			if(f.exists()) {
				f.delete();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//千年不变
	@SuppressWarnings("resource")
	public static byte[] readFileContent(String file) {
		try {
			FileInputStream fis = new FileInputStream(file);
			byte[] data = new byte[1024];
			int pos = 0;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while((pos=fis.read(data))!=1) {
				baos.write(data, 0, pos);
			}
			baos.close();
			return baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	//模拟调用方法
	public static void main(String[] args) {
		String ftlPath = "ftl";
		String ftlName = "good.ftl";
		String htmlPath = "html";
		Map map = new HashMap();
		map.put("id", 1);
		FreemarkerUtil.genHtml(null, ftlPath, ftlName, htmlPath, map);
	}
}
